(import (ice-9 popen)
        (ice-9 textual-ports)
        (ice-9 binary-ports)
        (ice-9 exceptions)
        (ice-9 receive)
        (ice-9 match))


(define read-from-write-to
  (lambda* (in-port out-port #:key (bytes-count 1024))
    "Read from an IN-PORT and write to OUT-PORT,
    BYTES-COUNT bytes at a time."
    (let loop ([bv (get-bytevector-n in-port bytes-count)])
      (unless (eof-object? bv)
        (put-bytevector out-port bv)
        (loop (get-bytevector-n in-port bytes-count))))))


;; Trying to allow the user to give output port and error
;; port to the function. But how to elegantly call it then?
(define run-command
  (lambda* (cmd
            #:key
            (cmd-out-port (current-output-port))
            (err-out-port (current-error-port)))
    (with-output-to-port cmd-out-port
      (λ ()
        (with-error-to-port err-out-port
          (λ ()
            (let* (;; Run the actual command. If an error
                   ;; happens, it should write to the
                   ;; err-write port. Output of the command
                   ;; should be written to an output port,
                   ;; which corresponds to the input-port,
                   ;; which is returned by open-input-pipe.
                   [in-port (open-input-pipe cmd)]
                   ;; Read in block mode.
                   [_ignored (setvbuf in-port 'block)])
              ;; Write to caller given command output port.
              (read-from-write-to in-port cmd-out-port)
              ;; Get the exit code of the command.
              (close-pipe in-port))))))))


(match-let ([(cmd-in . cmd-out) (pipe)]
            [(err-in . err-out) (pipe)])
  (let ([exit-code
         (run-command "ls -al"
                      #:cmd-out-port cmd-out
                      #:err-out-port err-out)])
    (close-port cmd-out)
    (close-port err-out)
    (let ([output-message (get-string-all cmd-in)]
          [error-message (get-string-all err-in)])
      (simple-format (current-output-port) "exit code: ~a\n" exit-code)
      (simple-format (current-output-port) "output message: \n~a" output-message)
      (simple-format (current-output-port) "error message: \n~a" error-message))))


(run-command "echo 'bong' 1>&2")
(run-command "ls -al")
(run-command "ls -al 2>&1 && echo 'bong' 1>&2")
(run-command "lsasdasd -al")
